<?php
/**
* socket test
socket live：
socket_create > socket_bind address and port > listen or connect
*/
//socket server

$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_bind($socket,'0.0.0.0',5000);
echo '000';
socket_listen($socket,2);
$clients = [$socket];
while(true)
{
	$read = $clients;
	$back = socket_select($read, $write=null, $except=null, 0);

	if (in_array($socket, $read)) {
        // accept the client, and add him to the $clients array
        $clients[] = $newsock = socket_accept($socket);
       
        // send the client a welcome message
        socket_write($newsock, "no noobs, but ill make an exception :)\n".
        "There are ".(count($clients) - 1)." client(s) connected to the server\n");
       
        socket_getpeername($newsock, $ip);
        echo "New client connected: {$ip}\n";
       
        // remove the listening socket from the clients-with-data array
        $key = array_search($socket, $read);
        unset($read[$key]);
    }

    if($back<1){
    	continue;
    }
    foreach($read as $conn){
    	$info = @socket_read($conn, 1024);
    	if($info === false){
    		$k = array_search($conn, $clients);
    		unset($clients[$k]);
    		continue;
    	}
    	echo $info.PHP_EOL;
    	socket_write($conn, 'test->return');
    }
}